'use strict'
require 'angular'
require 'angular-breadcrumb'
require 'angular-validation'
require 'angular-validation-rule'

app = angular.module 'core', [
  'ncy-angular-breadcrumb'
  'validation'
  'validation.rule'

  require 'angular-ui-router'
  require 'oclazyload'
  require('./controllers/index/index.coffee').name
  require('./controllers/index/message/index.coffee').name

  require('constant').name
  require('commonService').name
  require('sessionService').name
  require('interceptor').name
  require('yhPermissionDirective').name
  require('angularValidationSupportDirective').name
  require('dialogService').name
  require('accountService').name
  require('authEvents').name
]
.config ($urlRouterProvider, $validationProvider, $httpProvider)->
  $httpProvider.interceptors.push 'AuthInterceptor'
  $httpProvider.interceptors.push 'RequestInterceptor'
  $urlRouterProvider.otherwise '/index'

  # validation
  validExpression =
    mobile: /^(1)[0-9]{10}$/
  validMsg =
    required: error: '这个字段是必须的'
    url: error: '请输入合法的URL'
    email: error: '请输入合法的Email'
    number: error: '请输入合法的数字'
    minlength: error: '请输入至少 {0}个 字符'
    maxlength: error: '最多只允许输入 {0}个 字符'
    mobile: error: '请输入合法的手机号'
  $validationProvider.setExpression(validExpression).setDefaultMsg(validMsg)

.run ($log, $rootScope, $timeout, $interval, $http, $location, $state, DialogService, SessionService, Constant, CommonService, AccountService, AUTH_EVENTS)->
  dialogService = new DialogService()
  sessionService = new SessionService()
  commonService = new CommonService()
  accountService = new AccountService()
  constant = new Constant()
  $rootScope.$state = $state

#  禁止Quill对话框弹出
  Quill.modules['image-tooltip'].prototype._onToolbar = (range,value)->

  $rootScope.session = toPlatforms: {}

# 跳转登录平台
  _toLoginPlatform = -> window.location = constant.PLATFORM.login.url

# 是否带token参数
  _hasToken = (hasCallback, hasntCallback)->
    token = commonService.getUrlParam location.href, "token"
    return hasCallback token if hasCallback? and token?
    return hasntCallback() if hasntCallback?
# 验证会话是否有效
  _isAuthenticated = (successCallback, errorCallback)->
    accountService.isAuthenticated (user)->
      successCallback user if successCallback?
    , (error)->
      errorCallback error if errorCallback?

  _getSystemAuth = ->
    hasDecoAuth = false
    hasMallAuth = false
    hasHomeAuth = false
    hasJCAuth = false
    hasAdminAuth = false
    for system in sessionService.getSystems()
      if !hasDecoAuth and system is 'DECO'
        hasDecoAuth = true
        continue
      if !hasMallAuth and system is 'MALL'
        hasMallAuth = true
        continue
      if !hasHomeAuth and system is 'HOME'
        hasHomeAuth = true
        continue
      if !hasJCAuth and system is 'JIANCAI'
        hasJCAuth = true
        continue
      if !hasAdminAuth and (system is 'PASSPORT' or system is 'COMMON')
        hasAdminAuth = true
        continue
    result =
      hasDecoAuth: hasDecoAuth
      hasMallAuth: hasMallAuth
      hasHomeAuth: hasHomeAuth
      hasJCAuth: hasJCAuth
      hasAdminAuth: hasAdminAuth
    return result

  $rootScope.$on '$stateChangeStart', (event, next)->
    if !sessionService.initTokenHeader()
      _toLoginPlatform()
      event.preventDefault()
      return

    _isAuthenticated (user)->
      sessionService.setUser user
      sessionService.setAvatar user.avatar
      accountService.getPermissionSync {operatorUuid: user.uuid}, (permissions)->
        sessionService.setPermissions permissions
        systems = []
        systems.push permission.system.code for permission in permissions when systems.indexOf(permission.system.code) is -1
        sessionService.setSystems systems

      $rootScope.session.avatar = user.avatar
      auths = _getSystemAuth()
      if auths.hasDecoAuth
        $rootScope.session.toPlatforms.deco = constant.PLATFORM.deco
      if auths.hasMallAuth
        $rootScope.session.toPlatforms.mall = constant.PLATFORM.mall
      if auths.hasHomeAuth
        $rootScope.session.toPlatforms.home = constant.PLATFORM.home
      if auths.hasJCAuth
        $rootScope.session.toPlatforms.jiancai = constant.PLATFORM.jiancai
#      if auths.hasAdminAuth
#        $rootScope.session.toPlatforms.common = constant.PLATFORM.common
      if auths.hasAdminAuth
        $rootScope.session.passportRole = 'ADMIN'
    , ->
      _toLoginPlatform()

  $rootScope.$on '$stateChangeSuccess', (event, toState, toParams, fromState, fromParams)->
    $rootScope.session.user = sessionService.getUser()
    $rootScope.session.token = sessionService.getToken()
    $rootScope.session.permissions = sessionService.getPermissions()

  $rootScope.$on AUTH_EVENTS.notAuthenticated, (event)-> _toLoginPlatform()
  $rootScope.$on AUTH_EVENTS.logoutSuccess, (event)-> _toLoginPlatform()

  _hasToken (token)->
    sessionService.setToken token
    window.location = $location.absUrl().substring 0, $location.absUrl().indexOf("token=") - 1

  $rootScope.$on 'error', (event, response)->
    return if !response or !response.data
    if response.status is 500
      dialogService.notify title: '失败', content: '操作失败!请稍后再试!'
    if response && response.data && response.data["MESSAGE"]
      return if [30006].indexOf(response.data["CODE"]) isnt -1
#      dialogs.error("失败", response.data["MESSAGE"])

angular.element(document).ready -> angular.bootstrap document, ['core']

module.exports = app